<?php

namespace app\api\controller;

use app\api\server\Goods as ServerGoods;
use app\api\server\Order as ServerOrder;
use app\common\controller\Api;
use app\common\library\Express;
use app\common\model\Invoice;
use app\common\model\order\Goods;
use app\common\model\order\Order as OrderOrder;
use app\common\model\User;
use think\Db;
use think\Exception;
use think\Validate;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    /**
     * @Author LK
     * @date: 2023-11-13 
     * @ApiTitle (预支付订单)
     * @ApiMethod (POST)
     * @ApiParams (name="coupon_id", type="integer", required=true, sample="", description="优惠券ID")
     * @ApiParams (name="address_id", type="integer", required=true, sample="", description="地址ID")
     * @ApiParams (name="type", type="string", required=true, sample="", description="1=购物车购买,2=立即购买")
     * @ApiParams (name="cart_ids", type="integer", required=true, sample="", description="购物车ID（购物车购买）")
     * @ApiParams (name="goods_id", type="integer", required=true, sample="", description="商品id（立即购买）")
     * @ApiParams (name="spec_id", type="integer", required=true, sample="", description="规格（立即购买）")
     * @ApiParams (name="num", type="integer", required=true, sample="", description="数量（立即购买）")
     * @ApiParams (name="class", type="integer", required=true, sample="", description="类型:1=百村联盟,2=创业专区")
     * @ApiParams (name="meal", type="integer", required=true, sample="", description="套餐:0=否,1=是")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function yu_order()
    {
        $params = request()->param();
        try {
            $userinfo = $this->auth->getUser();
            $data = ServerOrder::yu_order($params, $userinfo);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('', $data);
    }

    /**
     * @Author LK
     * @date: 2023-11-13 
     * @ApiTitle (订单下单)
     * @ApiMethod (POST)
     * @ApiParams (name="coupon_id", type="integer", required=true, sample="", description="优惠券ID")
     * @ApiParams (name="address_id", type="integer", required=true, sample="", description="地址ID")
     * @ApiParams (name="type", type="string", required=true, sample="", description="1=购物车购买,2=立即购买")
     * @ApiParams (name="cart_ids", type="integer", required=true, sample="", description="购物车ID（购物车购买）")
     * @ApiParams (name="goods_id", type="integer", required=true, sample="", description="商品id（立即购买）")
     * @ApiParams (name="num", type="integer", required=true, sample="", description="数量（立即购买）")
     * @ApiParams (name="spec_id", type="integer", required=true, sample="", description="规格（立即购买）")
     * @ApiParams (name="content", type="integer", required=true, sample="", description="留言")
     * @ApiParams (name="class", type="integer", required=true, sample="", description="类型:1=百村联盟,2=创业专区")
     * @ApiParams (name="meal", type="integer", required=true, sample="", description="套餐:0=否,1=是")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function add_order()
    {
        $params = request()->param();
        try {
            $userinfo = User::get($this->auth->id);
            if ($userinfo->state == 0) {
                exception('账户已冻结，禁止交易');
            }
            $data = ServerOrder::yu_order($params, $userinfo);
            $data['content'] = $params['content'];
            $data['class'] = $params['class'];
            $data['meal'] = $params['meal'];
            $id = ServerOrder::add_order($data);
            queue('app\\common\\job\\CancelOrder', $id, 900, '1303cancelorder');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('', $id);
    }
    /**
     * 检测体验商品限购
     *
     * @ApiMethod (POST)
     * @param string $id    商品id
     * @param string $num   数量
     */
    public function check_goods()
    {
        $param = request()->param();
        $param['uid'] = $this->auth->id;
        try {
            OrderOrder::check_goods($param);
        } catch (\Exception $e) {
            if ($e->getCode() == 1) {
                $this->error('', $e->getMessage(), 1);
            } else {
                $this->error($e->getMessage());
            }
        }
        $this->success();
    }
    /**
     * @Author LK
     * @date: 2023-11-15 
     * @ApiTitle (订单列表)
     * @ApiMethod (GET)
     * @ApiParams (name="order_status", type="string", required=true, sample="", description="all=全部,0=待支付,10=待发货,20=待收货,30=已完成")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function order_list()
    {
        $params = request()->param();
        $lists = ServerOrder::order_list($params);
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @date: 2023-11-15 
     * @ApiTitle (订单详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function order_info()
    {
        $params = request()->param();
        extract($params);
        $lists = OrderOrder::get($id, ['goods' => function ($q) {
            $q->with(['spec']);
        }]);

        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @date: 2023-11-14 
     * @ApiTitle (取消订单)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function cancel_order()
    {
        $params = request()->param();
        extract($params);
        $order = OrderOrder::get($id);
        if ($order->order_status != '0') {
            $this->error('订单状态错误');
        }
        Db::startTrans();
        try {
            $order->order_status = '-1';
            $order->save();
            $lists = Goods::all(['order_id' => $order['id']]);
            foreach ($lists as $k => $v) {
                ServerGoods::stockUp($v['goods_id'], $v['spec_id'], $v['goods_num']);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }

    /**
     * @Author LK
     * @date: 2023-11-14 
     * @ApiTitle (删除订单)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function del_order()
    {
        $params = request()->param();
        extract($params);
        $order = OrderOrder::get($id);
        if ($order->order_status != '-1') {
            $this->error('订单还未取消，无法删除');
        }
        Db::startTrans();
        try {
            Goods::where('order_id', $order->id)->delete();
            $order->delete();
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
        }
        $this->success('成功');
    }


    /**
     * @Author LK
     * @date: 2023-10-23 
     * @ApiTitle (查看物流)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="type", type="string", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function logistics()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $order = OrderOrder::get($id);
        if (!$order) {
            $this->error('订单不存在');
        }
        $express = new Express($order);
        $wuliu = $express->getOrderTracesByJson();
        $wuliu['express_name'] = Db::name('express')->where('customer', $order['express_com'])->value('name');
        $wuliu['address'] = $order['address'];
        // $wuliu['city'] = $order['city'];
        $wuliu['nu'] = $order['express_no'];
        $this->success('', $wuliu);
    }
    /**
     * @Author LK
     * @date: 2023-11-16 
     * @ApiTitle (确认收货)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function take_order()
    {
        $params = request()->param();
        try {
            ServerOrder::take_order($params);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }



    /**
     * @Author LK
     * @date: 2023-10-20 
     * @ApiTitle (申请发票)
     * @ApiMethod (POST)
     * @ApiParams (name="order_id", type="integer", required=true, sample="", description="订单id")
     * @ApiParams (name="money", type="string", required=true, sample="", description="开票金额")
     * @ApiParams (name="class", type="string", required=true, sample="", description="发票类型:1=专用发票,2=普通发票")
     * @ApiParams (name="title", type="string", required=true, sample="", description="公司名称")
     * @ApiParams (name="identification", type="string", required=true, sample="", description="纳税人识别号")
     * @ApiParams (name="address", type="string", required=true, sample="", description="地址")
     * @ApiParams (name="phone", type="string", required=true, sample="", description="联系电话")
     * @ApiParams (name="account", type="string", required=true, sample="", description="银行账号")
     * @ApiParams (name="bank", type="string", required=true, sample="", description="开户行")
     * @ApiParams (name="email", type="string", required=true, sample="", description="电子邮箱")
     * @ApiParams (name="mark", type="string", required=true, sample="", description="备注")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function open_invoice()
    {
        $params = request()->param();
        extract($params);
        $rule = [
            'order_id' => 'require',
            'money' => 'require',
            'title' => 'require',
            'identification' => 'require',
            'address' => 'require',
            'phone' => 'require',
            'account' => 'require',
            'bank' => 'require',
            'email' => 'require|email',
        ];
        $msg = [
            'order_id.require' => '参数错误',
            'money.require' => '请输入开票金额',
            'title.require' => '请输入公司抬头',
            'identification.require' => '请输入税号',
            'address.require' => '请输入地址',
            'phone.require' => '请输入联系电话',
            'account.require' => '请输入银行账号',
            'bank.require' => '请输入开户行',
            'email.require' => '请输入接收邮箱',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($params);
        if (!$result) {
            $this->error($validate->getError());
        }
        $order = OrderOrder::get($order_id);
        if ($order && $order->taketime) {
            if (bcadd(config('site.expiration_day') * 86400, $order->taketime, 0) < time()) {
                $this->error('有效期已过，无法开票');
            };
        }
        Db::startTrans();
        try {
            $params['user_id'] = $this->auth->id;
            $data = Invoice::get(['user_id' => $this->auth->id, 'order_id' => $order_id]);
            if ($data) {
                if ($data->status == '0' || $data->status == '1') {
                    exception('已申请开票');
                }
                $data->allowField(true)->save($params);
            } else {
                Invoice::create($params);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('失败:' . $e->getMessage());
        }
        $this->success('成功');
    }
    /**
     * @Author LK
     * @date: 2023-11-28 
     * @ApiTitle (商品评价)
     * @ApiMethod (GET)
     * @ApiParams (name="evaluate", type="integer", required=true, sample="", description="0=待评价,1=已评价")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function goods_evaluate()
    {
        $params = request()->param();
        $params['uid'] = $this->auth->id;
        $lists = ServerOrder::goods_evaluate($params);
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @date: 2023-11-28 
     * @ApiTitle (商品评价)
     * @ApiMethod (post)
     * @ApiParams (name="goods_id", type="integer", required=true, sample="", description="商品id")
     * @ApiParams (name="order_id", type="integer", required=true, sample="", description="订单ID")
     * @ApiParams (name="order_goods_id", type="integer", required=true, sample="", description="订单商品ID")
     * @ApiParams (name="star", type="integer", required=true, sample="", description="星级")
     * @ApiParams (name="description", type="string", required=true, sample="", description="描述")
     * @ApiParams (name="images", type="string", required=true, sample="", description="图片")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function evaluate()
    {
        $params = request()->param();
        $params['uid'] = $this->auth->id;
        try {
            $lists = ServerOrder::evaluate($params);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('', $lists);
    }

    /**
     * @Author LK
     * @date: 2023-11-06 
     * @ApiTitle (开票记录)
     * @ApiMethod (GET)
     * @ApiParams (name="status", type="integer", required=true, sample="", description="状态值:all=全部,0=开票中,1=开票成功,2=开票失败")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function billing_record()
    {
        $param = request()->param();
        extract($param);
        $model = new Invoice;
        if ($status != 'all') {
            $model->where('status', $status);
        }
        $lists = $model->where('user_id', $this->auth->id)->order('id desc')->paginate();
        $this->success('', $lists);
    }

    /**
     * @Author LK
     * @date: 2023-11-06 
     * @ApiTitle (发票详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function invoice_info()
    {
        $param = request()->param();
        extract($param);
        $info = Invoice::get($id);
        $this->success('', $info);
    }
}
